﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace RainmeterCustomized
{
    class IniRWTool
    {
        /// <summary>   
        /// 获取所有节点名称(Section)   
        /// </summary>   
        /// <param name="lpszReturnBuffer">存放节点名称的内存地址,每个节点之间用\0分隔</param>   
        /// <param name="nSize">内存大小(characters)</param>   
        /// <param name="filePath">Ini文件</param>   
        /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>   
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string filePath);

        /// <summary>   
        /// 获取某个指定节点(Section)中所有KEY和Value   
        /// </summary>   
        /// <param name="section">节点名称</param>   
        /// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>   
        /// <param name="nSize">内存大小(characters)</param>   
        /// <param name="filePath">Ini文件</param>   
        /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>   
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSection(string section, IntPtr lpReturnedString, uint nSize, string filePath);

        /// <summary>
        ///  获取指定的键值内容
        /// </summary>
        /// <param name="lpAppName"></param>
        /// <param name="lpKeyName"></param>
        /// <param name="lpDefault"></param>
        /// <param name="lpReturnedString"></param>
        /// <param name="nSize"></param>
        /// <param name="lpFileName"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName);  
  
        /// <summary>
        /// 将指定的val值写入指定的键
        /// </summary>
        /// <param name="section">节点名称</param>
        /// <param name="key">键名</param>
        /// <param name="val">键值</param>
        /// <param name="filePath">文件名</param>
        /// <returns>写入结果</returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        /// <summary>
        /// 将指定键值对写入到指定章节，可写注释
        /// </summary>
        /// <param name="section">章节</param>
        /// <param name="item">内容</param>
        /// <param name="filePath">文件名</param>
        /// <returns>写入的长度， 0表示失败</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]     //可以没有此行   
        private static extern bool WritePrivateProfileSection(string section, string item, string filePath);  

        /// <summary>
        /// 读取指定章节指定键名的键值
        /// </summary>
        /// <param name="section">章节名</param>
        /// <param name="key">键名</param>
        /// <param name="def">读取失败返回的默认值</param>
        /// <param name="retVal">存储读取结果的对象</param>
        /// <param name="size">读取大小</param>
        /// <param name="filePath">文件路径</param>
        /// <returns>读取结果</returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        private String filePath;
        public IniRWTool(String filePath)
        {
            this.filePath = filePath;
        }

        /// <summary>
        /// 写入ini，指定章节、键值对，不存在则添加，存在则覆盖
        /// </summary>
        /// <param name="section">章节</param>
        /// <param name="key">键名</param>
        /// <param name="val">键值</param>
        /// <returns>写入结果，是否成功</returns>
        public Boolean WriteValue(string section, string key, string val)
        {
            if (val.Length > 255) return false;
            long length = WritePrivateProfileString(section, key, val, this.filePath);
            if (length == 0) return false;
            return true;
        }

        /// <summary>
        /// 读取指定章节和键名的键值
        /// </summary>
        /// <param name="section">章节</param>
        /// <param name="key">键值</param>
        /// <returns>键值，不存在则返回空</returns>
        public String GetValue(string section, string key)
        {
            StringBuilder temp = new StringBuilder();
            GetPrivateProfileString(section, key, "", temp, 255, this.filePath);
            return temp.ToString()+"";
        }

        /// <summary>
        /// 获取所有的章节
        /// </summary>       
        /// <returns>章节的String列表</returns>
        public String[] GetSections()
        {
            uint MAX_BUFFER = 32767;    //默认为32767   
            string[] sections = new string[0];      //返回值   

            //申请内存   
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, this.filePath);
            if (bytesReturned != 0)
            {
                //读取指定内存的内容   
                string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();

                //每个节点之间用\0分隔,末尾有一个\0   
                sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }

            //释放内存   
            Marshal.FreeCoTaskMem(pReturnedString);

            return sections;
        }

        /// <summary>
        /// 获取指定章节的KeyValue键值对
        /// </summary>
        /// <param name="section">章节名</param>
        /// <returns>键值对数组</returns>
        public String[] GetKeyValues(String section)
        {
            //返回值形式为 key=value,例如 Color=Red   
            uint MAX_BUFFER = 32767;    //默认为32767   

            string[] items = new string[0];      //返回值   

            //分配内存   
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));

            uint bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, this.filePath);

            if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
            {

                string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
                items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }

            Marshal.FreeCoTaskMem(pReturnedString);     //释放内存   

            return items;  
        }

        /// <summary>
        /// 获取指定章节的键名列表  **** 未完成
        /// </summary>
        /// <param name="section">章节</param>
        /// <returns>键名列表</returns>
        public String[] GetKeys(String section)
        {
            String[] keys = new String[0];
           
            return keys;
        }

        /// <summary>
        /// 将指定内容写入指定章节
        /// </summary>
        /// <param name="section">章节</param>
        /// <param name="item">内容</param>
        /// <returns>写入结果</returns>
        public Boolean WriteItems(String section, String item)
        {
            if (String.IsNullOrEmpty(section) || String.IsNullOrEmpty(item)) return false;
            return WritePrivateProfileSection(section, item, this.filePath);
        }

        /// <summary>
        /// 删除指定章节的键
        /// </summary>
        /// <param name="section">章节</param>
        /// <param name="key">键</param>
        /// <returns>删除结果</returns>
        public Boolean DelKey(String section, String key)
        {
            if (String.IsNullOrEmpty(section) || String.IsNullOrEmpty(key)) return false;

            return WriteValue(section, key, null);
        }

        /// <summary>
        /// 删除指定章节所有键对
        /// </summary>
        /// <param name="section">章节</param>
        /// <returns>删除结果</returns>
        public Boolean DelSection(String section)
        {
            if (String.IsNullOrEmpty(section)) return false;
            long length = WritePrivateProfileString(section, null, null, this.filePath);
            if (length == 0) return false;
            return true;
        }

        /// <summary>
        /// 清空章节
        /// </summary>
        /// <param name="section">章节</param>
        /// <returns>清空结果</returns>
        public Boolean EmptySection(String section)
        {
            if (String.IsNullOrEmpty(section)) return false;
            return WritePrivateProfileSection(section, string.Empty, this.filePath); 
        }

    }
}
